#include "StdAfx.h"
#include <vector>
#include <iostream>
#include "time.h"
#include "PerformanceMonitor.h"

PerformanceMonitor::PerformanceMonitor(void)
{
}

PerformanceMonitor::~PerformanceMonitor(void)
{
}

static void received(std::map<long, int>& map, int length)
{
	map[clock()] = length;
}

void PerformanceMonitor::ReceivedModulator(int length)
{
	received(modulatorReceived, length);
}

void PerformanceMonitor::ReceivedVocoded(int length)
{
	received(vocodedReceived, length);
}

static void getTimeOfSampleBlocks(std::map<long, int>& timerMap, int blockSize, std::vector<long>& results)
{
	int sum = 0;
	int blocksTotal = 0;
	for (std::map<long, int>::iterator it = timerMap.begin(); it != timerMap.end(); it++)
	{
		while(sum >= blocksTotal)
		{
			results.push_back(it->first);
			blocksTotal += blockSize;
		}
		sum += it->second;
	}
}

static void calculateLag(std::map<long, int>& map1, std::map<long, int>& map2)
{
	std::vector<long> map1Times;
	std::vector<long> map2Times;
	getTimeOfSampleBlocks(map1, 1000, map1Times);
	getTimeOfSampleBlocks(map2, 1000, map2Times);

	unsigned int len = map1Times.size() < map2Times.size() ? map1Times.size() : map2Times.size();
	std::vector<long> lags(len);
	for(unsigned int i=0; i<len; i++)
	{
		long lag = map2Times[i] - map1Times[i];
		lags[i] = lag;
	}
	
	long lagSum = 0;
	for(unsigned int i=0; i<lags.size(); i++)
	{
		lagSum += lags[i];
	}
	if(lags.size())
	{
		unsigned int avgLag = lagSum / lags.size();
		std::cout << lagSum << std::endl;
	}
}

void PerformanceMonitor::CalculateModulatorVocodedLag()
{
	std::cout << "Modulator->Vocoded lag" << std::endl;
	calculateLag(modulatorReceived, vocodedReceived);
}
